package com.shujia.kafka;

import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;

import java.util.ArrayList;
import java.util.Properties;

public class Demo02KafkaConsumer {
    public static void main(String[] args) throws InterruptedException {

        Properties properties = new Properties();
        properties.setProperty("bootstrap.servers", "master:9092,node2:9092,node2:9092");
        properties.setProperty("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        properties.setProperty("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        /*
         * earliest
         * 当各分区下有已提交的offset时，从提交的offset开始消费；无提交的offset时，从头开始消费
         * latest  默认
         * 当各分区下有已提交的offset时，从提交的offset开始消费；无提交的offset时，消费新产认值生的该分区下的数据
         * none
         * topic各分区都存在已提交的offset时，从offset后开始消费；只要有一个分区不存在已提交的offset，则抛出异常
         *
         */
        properties.setProperty("auto.offset.reset", "earliest");
        properties.setProperty("group.id", "asdasd");

        KafkaConsumer<String, String> consumer = new KafkaConsumer<>(properties);

        ArrayList<String> topics = new ArrayList<>();
        topics.add("t1");

        // 先订阅Topic
        consumer.subscribe(topics);
        while(true){
            // 拉取数据
            ConsumerRecords<String, String> records = consumer.poll(100);

            // 遍历数据
            for (ConsumerRecord<String, String> record : records) {
                String key = record.key();
                long offset = record.offset();
                String value = record.value();
                int partition = record.partition();
                long timestamp = record.timestamp();

                System.out.println("key:" + key + ","+"offset:" + offset + ","+"value:" + value+ ","+"partition:" + partition+ ","+"timestamp:" + timestamp);
            }

            Thread.sleep(1000);
        }




    }
}
